#!/usr/bin/env python

"""
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
"""

import imp
import subprocess
import os
import shutil
import stat
from zipfile import ZipFile
import glob

def clearReadOnlyAttribute(dir):
  for (currentDir, dirs, files) in os.walk(dir):
    for f in files:
      os.chmod(os.path.join(currentDir, f), stat.S_IWRITE)

tools = imp.new_module("tools")
execfile(os.path.join("..", "iren-deps", "tools.py"), tools.__dict__)

build = "build"
if os.path.exists(build):
  clearReadOnlyAttribute(build)
  shutil.rmtree(build)

serverTarget = os.path.join(build, "server")
shutil.copytree(tools.jre, serverTarget)
os.rename(os.path.join(serverTarget, "bin", "java.exe"),
    os.path.join(serverTarget, "bin", "irenServer.exe"))

for f in glob.iglob(os.path.join("..", "iren-deps", "*.zip")):
  with ZipFile(f, "r") as zip:
    zip.extractall(serverTarget)
  
protoSource = os.path.join("server", "src", "ru", "irenproject")
protoTarget = os.path.join(serverTarget, "generated-protos")
os.makedirs(protoTarget)

for (currentDir, dirs, files) in os.walk(protoSource):
  for f in files:
    if os.path.splitext(f)[1] == ".proto":
      subprocess.check_call([tools.protobufCompiler, "--java_out=" + protoTarget,
          "--proto_path=" + protoSource, "--proto_path=" + tools.protobufSource,
          os.path.join(currentDir, f)])

shutil.copy(tools.upx, build)
shutil.copytree(os.path.join(tools.lazarus, "lcl", "languages"),
    os.path.join(build, "lcl-languages"))

with ZipFile(tools.ecj) as zip:
  zip.extract("jdtCompilerAdapter.jar", build)

os.makedirs(os.path.join(serverTarget, "compiled-classes"))
